<?php

namespace Home\Controller;
use Think\AjaxPage;
use Think\Page;
use Think\Verify;
use Home\Logic\CompanyCatLogic;
class AdminController extends BaseController {

    
    /* public function index(){
        $this->display();
    } */
    
    /**
     * 用户列表
     */
    public function index(){
        $model = M('admin');
        $cor = M('company_cat');
        $res = $model->order('last_login desc')->select();
        $role = M('admin_role')->getField('role_id,role_name');
        $cat = $cor->getField('cat_id,cat_name');
        $depart = array(1=>'设计',2=>'咨询',3=>'监理',4=>'施工企业',5=>'建设单位');
        if($res && $role && $cat){
            foreach ($res as $val){
                $val['company'] = $cat[$val['company']];
                $val['department'] = $depart[$val['department']];
                $val['role'] =  $role[$val['role_id']];
                $val['add_time'] = date('Y-m-d H:i:s',$val['add_time']);
                $userList[] = $val;
            }
        }
        $rolee = M('admin_role')->field('role_id,role_name')->select();
        /* $corporate = $cor->where('parent_id=0')->select();
        foreach ($corporate as $key=>$val){
           $corporate[$key]['post'] = $model->field('admin_id,name')->where(array('company'=>$val['cat_id']))->select();
        } */
        $corporate= A('project')->member();
        $this->assign('corporate',$corporate);
        $this->assign('role',$rolee);
        $this->assign('userList',$userList);
        $this->assign('cat_name',$cat_name);
        $this->display();
    }
    
    /*
     * ajax点击详情
     */
    public function indexdetail(){
        $where=array();
        $cat_id = I('post.admin_id');
        if(!$cat_id){
            $this->error('id不能为空');
        }
        $model = M('admin');
        $userList = $model->where('admin_id='.$cat_id)->order('last_login desc')->select();
        $role = M('admin_role')->getField('role_id,role_name');
        $cat = M('company_cat')->getField('cat_id,cat_name');
        $depart = array(1=>'设计',2=>'咨询',3=>'监理',4=>'施工企业',5=>'建设单位');
        if($userList && $role && $cat){
            foreach ($userList as $val){
                $val['company'] = $cat[$val['company']];
                $val['department'] = $depart[$val['department']];
                $val['role'] =  $role[$val['role_id']];
                $val['add_time'] = date('Y-m-d H:i:s',$val['add_time']);
                $res[] = $val;
            }
        }
        $this->assign('userList',$res);
        $this->display();
    }
    
    /*
     * 管理员登陆
     */
    public function login(){
   /*      if(session('?admin_id') && session('admin_id')>0){
             $this->error("您已登录",U('Index/index'));
        } */
      
        if(IS_POST){
            $verify = new Verify();
            if (!$verify->check(I('post.verify'), "admin_login")) {
            	exit(json_encode(array('status'=>0,'msg'=>'验证码错误')));
            } 
            $condition['user_name'] = I('post.username');
            $condition['password'] = I('post.password');
            if(!empty($condition['user_name']) && !empty($condition['password'])){
                $condition['password'] = encrypt($condition['password']);
               	$admin_info = M('admin')->join('__ADMIN_ROLE__ ON __ADMIN__.role_id=__ADMIN_ROLE__.role_id')->where($condition)->find();
                if(is_array($admin_info)){
                    session('admin_id',$admin_info['admin_id']);
                    session('role',$admin_info['role_id']);
                    session('act_list',$admin_info['act_list']);
                    session('admin',$admin_info);
                    $last_login_time = M('admin_log')->where("admin_id = ".$admin_info['admin_id']." and log_info = '后台登录'")->order('log_id desc')->limit(1)->getField('log_time');
                    M('admin')->where("admin_id = ".$admin_info['admin_id'])->save(array('last_login'=>time(),'last_ip'=>  getIP()));
                    session('last_login_time',$last_login_time);                            
                    adminLog('用户登录',__ACTION__);
                    $this->project();
                    $url = session('from_url') ? session('from_url') : U('Index/index');
                    exit(json_encode(array('status'=>1,'url'=>$url)));
                }else{
                    exit(json_encode(array('status'=>0,'msg'=>'账号密码不正确')));
                }
            }else{
                exit(json_encode(array('status'=>0,'msg'=>'请填写账号密码')));
            }
        }
        $this->display();
    }
    
    /**
     * 获取当前的项目和可以切换的项目
     */
    public function project(){
        $uid = session('admin_id');
        $where = array();
        $Modal = M('project');
        $sql = "SELECT product_id FROM setpm WHERE find_in_set($uid, `join`)";
        $join = M('')->query($sql);
        if($join){
            foreach ($join as $key=>$val){
                $pid[] = $val['product_id'];
            }
            $pid = implode(',',$pid);
            $map['id'] = array('in',$pid);
            $where = implode(' AND ', $where);
            $dat = $Modal->field('id,name,total_ren')->where($map)->select();
        }
        $da = $Modal->field('id,name,total_ren')->where('total_ren='.$uid)->order('add_time asc')->select();
        if($da){
            session('pid',$da[0]['id']);
            session('pname',$da[0]['name']);
        }else{
            session('pid',$dat[0]['id']);
            session('pname',$dat[0]['name']);
        }
    }
    
    /**
     * 新增和编辑数据
     */
    public function admin_info(){
        $admin_id = I('admin_id',0);
        if($admin_id){
            $info = D('admin')->where("admin_id=$admin_id")->find();
            $info['password'] =  "";
            $this->assign('info',$info);
        }
        $act = empty($admin_id) ? 'add' : 'edit';
        $this->assign('act',$act);
        $role = D('admin_role')->where('1=1')->select();
        $this->assign('role',$role);
        $this->display('index');
    }
    
    /**
     * 退出登陆
     */
    public function logout(){
        session_unset();
        session_destroy();
        $this->success("退出成功",U('Admin/login'));
    }
    
    /**
     * 验证码获取
     */
    public function verify()
    {
        $config = array(
            'fontSize' => 30,
            'length' => 4,
            'useCurve' => true,
            'useNoise' => false,
        	'reset' => false
        );    
        $Verify = new Verify($config);
        $Verify->entry("admin_login");
    }
    
    /**
     * 角色列表
     */
    public function role(){
    	$list = D('admin_role')->order('role_id desc')->select();
    	$this->assign('list',$list);
    	$this->display();
    }
    /**
     * 角色信息
     */
    public function role_info(){
    	$role_id = I('get.role_id');
    	$tree = $detail = array();
    	if($role_id){
    		$detail = M('admin_role')->where("role_id=$role_id")->find();
    		$detail['act_list'] = explode(',', $detail['act_list']);
    		$this->assign('detail',$detail);
    	}
		$right = M('system_menu')->order('id')->select();
		foreach ($right as $val){
			if(!empty($detail)){
				$val['enable'] = in_array($val['id'], $detail['act_list']);
			}
			$modules[$val['group']][] = $val;
		}
		//权限组
		$group = array('system'=>'系统设置','plan'=>'计划管理','quality'=>'质量管理','cost'=>'成本管理','project'=>'项目管理','bim'=>'BIM管理','family' => '族库管理'
     	);
		$this->assign('group',$group);
		$this->assign('modules',$modules);
    	$this->display();
    }
    
    /**
     * 角色保存
     */
    public function roleSave(){
    	$data = I('post.');
    	$res = $data['data'];
    	$res['act_list'] = is_array($data['right']) ? implode(',', $data['right']) : '';
    	if(empty($data['role_id'])){
    		$r = D('admin_role')->add($res);
    		adminLog('添加角色',__ACTION__);
    	}else{
    		$r = D('admin_role')->where('role_id='.$data['role_id'])->save($res);
    		adminLog('编辑角色',__ACTION__);
    	}
		if($r){
			$this->success("操作成功!",U('Admin/role'));
		}else{
			$this->success("操作失败!",U('Admin/role'));
		}
    }
    
    /**
     * 删除角色
     */
    public function roleDel(){
    	$role_id = I('post.role_id');
    	$admin = D('admin')->where('role_id='.$role_id)->find();
    	if($admin){
    		exit(json_encode("请先清空所属该角色的管理员"));
    	}else{
    		$d = M('admin_role')->where("role_id=$role_id")->delete();
    		if($d){
    		    adminLog('删除角色',__ACTION__);
    			exit(json_encode(1));
    		}else{
    			exit(json_encode("删除失败"));
    		}
    	}
    }
    
    /**
     * 用户列表
     */
     public function log(){  
       $this->display();
    } 
    
    /**
     * ajaxlog
     */
    public function ajaxlog(){
        // 搜索条件
        $user = M('admin')->getField('user_name,name');
        $Log = M('admin_log');
        $condition = array();
        $count =  $Log->count();
        $Page  = new AjaxPage($count,15);
        //  搜索条件下 分页赋值
        foreach($condition as $key=>$val) {
            $Page->parameter[$key]   =   urlencode($val);
        }
        $logs = $Log->join('__ADMIN__ ON __ADMIN__.admin_id =__ADMIN_LOG__.admin_id')->order('log_time DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
        $show = $Page->show();
        $this->assign('list',$logs);
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('user',$user);
        $this->display();
    }
    
    
    /**
     * 删除会员
     */
    public function delete(){
        $uid = I('get.id');
        $row = M('admin')->where(array('admin_id'=>$uid))->delete();
        if($row){
            adminLog('删除用户列表',__ACTION__);
            $this->success('成功删除');
        }else{
            $this->error('操作失败');
        }
    }
    
    /**
     * 头像视图页
     */
    public function potrait(){
        $this->display();
    }
    
    /**
     * 头像上传
     */
    public function uploadImg(){
        if (IS_POST) {
            header('Content-Type: text/html; charset=utf-8');
            $result = array();
            $msg = '';
            $path='Uploads'.'/avatar/';
            $id = session('admin_id');
            /* if (file_exists($path)) {
             delDir($path);
            } */
            $avatars = array("__avatar1");
            $avatar = $_FILES[$avatars['0']];
            if ($avatar['error'] > 0 ){
                $msg .= $avatar['error'];
            }
            if(!file_exists($path)){
                makeDir($path);
            }
            $savePath = $path . date('Y').date('m').date('d').mt_rand() . ".jpg";
            if(move_uploaded_file($avatar["tmp_name"], $savePath)){
                $savePath = '/'.$savePath;
                M('admin')->where('admin_id='.$id)->save(array('img'=>$savePath));
                $result['msg'] = $msg;
                $result['success'] = true;
                adminLog("上传头像",__ACTION__);
                echo json_encode($result);
            }else{
                $result['success'] = false;
            }
        }
    }
    
    /**
     * 文件上传
     */
    public function upload(){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg','xlsx','xls','doc','docx','rar','zip','exe','txt','pdf');// 设置附件上传类型
        $upload->rootPath  =     './Uploads/file/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        $upload->saveName  =     array('uniqid','');
        // 上传文件 
        $info   =   $upload->upload();
        $a = explode(".",$info['photo']['name']);
        $hname = $a[0];
        if(!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        }else{// 上传成功
            $info = $info['photo'];
            $info['savepath'] = '/Uploads/file/'.$info['savepath'];
            M('file_download')->add(array('file_path'=>$info['savepath'],'hname'=>$hname,'name'=>$info['name'],'add_time'=>time(),'mname'=>$info['savename'],'ext'=>$info['ext']));
            adminLog("上传文件".$info['name']."成功",__ACTION__);
            $this->success('上传成功！');
        }
    }
    
   /**
    * 添加用户
    */
    public function adduser(){
        $data = I('post.');
        $eid = $_GET['eid'];
        if(is_numeric($eid)){
            $er = M('company_cat')->field('cat_id,cat_name')->where('parent_id ='.$eid)->select();
            $this->ajaxReturn(json_encode($er));
        }
        if(empty($data['password'])){
            unset($data['password']);
            exit(json_encode(array('errNo'=>1,'msg'=>'密码不能为空')));
        }else{
            $data['password'] = encrypt($data['password']);
        }
        
        $data['add_time'] = time();
        $data['img'] = "/Uploads/avatar/20170207418946823.jpg";
        if(M('admin')->where("name='".$data['name']."'")->count()){
            exit(json_encode(array('errNo'=>1,'msg'=>'此用户名已注册,请更换')));
        }
        if(M('admin')->where("user_name='".$data['user_name']."'")->count()){
             exit(json_encode(array('errNo'=>1,'msg'=>'此手机号已注册,请更换')));
        }else{
            $r = M('admin')->add($data);
            adminLog("新增用户".$data['user_name']."成功",__ACTION__);
            exit(json_encode(array('errNo'=>0,'msg'=>'新增成功')));
        }
    }
    
    /**
     * 编辑用户
     */
    public function edituser(){
        $data = I('post.');
        if(empty($data['password'])){
            unset($data['password']);
        }else{
            $data['password'] = encrypt($data['password']);
        }
        if($data['department'] == 0 ){
            unset($data['department']);
        }
        if($data['post'] == ''){
            unset($data['post']);
        }
        $r = M('admin')->where('admin_id='.$data['admin_id'])->save($data);
        if($r){
            adminLog("编辑用户".$data['user_name']."成功",__ACTION__);
            exit(json_encode(array('errNo'=>0,'msg'=>'修改成功')));
        }else{
            adminLog("编辑用户".$data['user_name']."失败",__ACTION__);
            exit(json_encode(array('errNo'=>1,'msg'=>'修改失败')));
        }
    }
    
    /**
     * 删除用户
     */
    public function deluser(){
        $id = I('post.id');
        if(!is_numeric($id)){
            exit(json_encode(array('errNo'=>1,'msg'=>'id不能为空')));
        }
        $rs = M('admin')->field("user_name")->where('admin_id='.$id)->find();
        $r = M('admin')->where('admin_id='.$id)->delete();
        if($r){
            adminLog("删除用户".$rs['user_name']."成功",__ACTION__);
            exit(json_encode(array('errNo'=>0,'msg'=>'删除成功')));
        }else{
            adminLog("删除用户".$rs['user_name']."失败",__ACTION__);
            exit(json_encode(array('errNo'=>1,'msg'=>'删除失败')));
        }
    }
    
    /**
     * 公司列表
     */
    public function company(){
        $modal = M('company_cat');
        $p = I('p',1);
        $data = $modal->where('parent_id=0')->page($p.',15')->select();
        $count = $modal->where('parent_id=0')->count();
        $Page = new \Think\Page($count,15);
        $show = $Page->show();
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('data',$data);
        $this->display();
    }
    
    /**
     * 新建公司
     */
    public function add_company(){
            $Modal= M('company_cat');
            $data['cat_name'] = I('post.cat_name');
            $data['parent_id'] = 0;
            $da = $Modal->field('cat_name')->where(array('cat_name'=>$data['cat_name']))->count();
             if($da){
                 exit(json_encode(array('errNo'=>1,'msg'=>'公司已存在,请勿重复创建')));
              }
            $result = $Modal->add($data);
            if($result){
                exit(json_encode(array('errNo'=>0,'msg'=>'创建成功')));
            }else{
                exit(json_encode(array('errNo'=>1,'msg'=>'创建失败')));
            }
    }
    
    /**
     * 编辑公司
     */
    public function edit_company(){
        $Modal= M('company_cat');
        $cat_id = I('post.cat_id');
        $cat_name = I('post.cat_name');
        $id = I('post.id');
        if($id!=0){
            $us = M('admin')->where(array('company'=>$id))->count();
            if($us){
                exit(json_encode(array('errNo'=>1,'msg'=>'请先删除所属公司用户')));
            }
           $r = $Modal->where('cat_id='.$id)->delete();
           if($r){
                  exit(json_encode(array('errNo'=>0,'msg'=>'删除成功')));
               }else{
                   exit(json_encode(array('errNo'=>1,'msg'=>'删除失败')));
           }
        }else{
            if(!is_numeric($cat_id)){
                exit(json_encode(array('errNo'=>1,'msg'=>'类目ID不能为空')));
            }
            $result = $Modal->where('cat_id='.$cat_id)->save(array('cat_name'=>$cat_name));
            if($result){
                exit(json_encode(array('errNo'=>0,'msg'=>'修改成功')));
            }else{
                exit(json_encode(array('errNo'=>1,'msg'=>'修改失败')));
            }
        }
     
    }
    
    /**
     * 修改密码
     */
    public function editpwd(){
        if(IS_POST){
            $ypas = I('post.ypas');
            $password = I('post.pas');
            if(empty($password)){
                exit(json_encode(array('errNo'=>1,'msg'=>'密码不能为空')));
            }
            $uid = session('admin_id');
            $ypas = encrypt($ypas);
            $p = M('admin')->field('password')->where('admin_id='.$uid)->find();
            if($ypas != $p['password']){
                exit(json_encode(array('errNo'=>1,'msg'=>'原密码不正确')));
            }
               $pas = encrypt($password);
               $res = M('admin')->where('admin_id='.$uid)->save(array('password'=>$pas));
               if($res){
                   exit(json_encode(array('errNo'=>0,'msg'=>'修改成功')));
               }else{
                   exit(json_encode(array('errNo'=>1,'msg'=>'修改失败')));
               }
            
        }
        $this->display();
    }
}